package udp

import (
	"log"
	"net"
	"screenRobot/network"
	"time"
)

var ListenEnabled = true

// ScanClient 用于扫描局域网中客户端
func ScanClient() {
	if !ListenEnabled {
		return
	}
	addr, err := net.ResolveUDPAddr("udp", "255.255.255.255:6970")
	if network.Handler("解析地址异常", err) {
		return
	}
	lAddr, err := net.ResolveUDPAddr("udp", ":6970")
	if network.Handler("解析地址异常", err) {
		return
	}

	conn, err := net.DialUDP("udp", nil, addr)
	if network.Handler("创建连接异常", err) {
		return
	}

	go func() {
		for {
			<-time.Tick(time.Second * 2)
			if !ListenEnabled {
				break
			}
			_, err = conn.Write([]byte("dpengchen@163.com"))
			if network.Handler("发送信息异常", err) {
				continue
			}
			log.Println("发送成功")
		}
	}()

	lConn, err := net.ListenUDP("udp", lAddr)
	if network.Handler("创建udp监听失败", err) {
		return
	}
	buffer := make([]byte, 1024)

	//开始获取其他客户端信息
	go func() {
		for {
			if !ListenEnabled {
				break
			}
			size, rAddr, err := lConn.ReadFromUDP(buffer)
			if network.Handler("读取信息异常", err) {
				continue
			}

			//如果端口不是其他客户端的则舍弃信息
			if rAddr.Port != 6970 {
				continue
			}

			//其他客户端的信息
			log.Printf("[%s]响应消息：%s", rAddr, buffer[:size])
		}
	}()
}
